package io.openmessaging.io;

import java.nio.ByteBuffer;

/**
 * IO抽象类
 *
 * @author cuijd    2021/10/12 13:58
 */
public interface IO extends AutoCloseable {
    /**
     * 已经写入的数据大小
     */
    long size();

    /**
     * 删除文件或释放内存
     */
    void delete();

    /**
     * 读满并 flip dst 缓冲区
     * 如果剩余数据不足以装满缓冲区，会抛出异常
     */
    default int readAndFlip(ByteBuffer dst, long position) {
        try {
            return read(dst, position);
        } finally {
            dst.flip();
        }
    }

    int read(ByteBuffer dst, long position);

    default void copyFrom(IO src, long srcOffset, long length) {
        throw new RuntimeException("not support");
    }

    /**
     * 从文件结尾追加
     *
     * @return 返回追加前的文件大小
     */
    long write(ByteBuffer... buffers);

    default void force() {
        throw new RuntimeException("not support");
    }

    default void close() {
        throw new RuntimeException("not support");
    }
}
